package com.innovativethinking.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.innovativethinking.domain.BufferName;
import com.innovativethinking.domain.KanbanTweet;
import com.innovativethinking.domain.service.KanbanTweetService;
import com.innovativethinking.web.name.RequestAttributeName;

@SuppressWarnings("serial")
@Singleton
public class KanbanTweetServlet extends HttpServlet {
	
	@Inject private UserService userService;
	
	@Inject private KanbanTweetService ktService = null;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		
		RequestDispatcher dispatcher = dispatcher2Home(req);
		
		dispatcher.forward(req, resp);		
	}

	private RequestDispatcher dispatcher2Home(HttpServletRequest req) {
		
		User user = activeUser(req);
		
		String buffer = getBuffer(req);
		
		List<KanbanTweet> tweets = ktService.getMyTweetsByBuffer(buffer, user);
		
		req.setAttribute(RequestAttributeName.TWEETS, tweets);
		
		req.setAttribute(RequestAttributeName.BUFFER, buffer);
		
		req.setAttribute(RequestAttributeName.USER, user);
		
		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/jsp/index.jsp");
		
		return dispatcher;
	}
	
	private String getBuffer(HttpServletRequest req) {
		
		if (req.getQueryString() != null && !req.getQueryString().startsWith(RequestAttributeName.KANBAN_ID)) {
			return req.getParameter(RequestAttributeName.BUFFER);
		}
		
		String buffer = (String) req.getAttribute(RequestAttributeName.BUFFER);
		
		if (buffer != null) return buffer;
		
		return BufferName.INPUTQUEUE;
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		
		String kanban = req.getParameter("kanban");
		
		User user = activeUser(req);
		
		KanbanTweet tweet = new KanbanTweet(kanban, user);
		
		ktService.save(tweet);
		
		//RequestDispatcher dispatcher = dispatcher2Home(req);
		//dispatcher.forward(req, resp);
		doGet(req, resp);
	}

	private User activeUser(HttpServletRequest req) {
		return userService.getCurrentUser();
	}	
}
